package com.headcaselabs.orchestra;

import java.util.List;

import junit.framework.JUnit4TestAdapter;
import junit.framework.TestCase;

import org.junit.Test;

import com.headcaselabs.queue.SQSUtils;
import com.headcaselabs.work.TestUnitOfWork;
import com.headcaselabs.work.UnitOfWork;

public class QueueTest extends TestCase {
	
	public final static String TEST_QUEUE = "testQueue";
	public final static String CONF_FILE = "conf.xml";
	private Configuration conf;
	
	private SQSUtils utils;
	
	public QueueTest() {
		System.out.println("Initializing configuration...");
		conf = Configuration.getConfiguration(CONF_FILE);
		utils = new SQSUtils(conf);
		System.out.println("Initialized configuration!");
	}
	
	
	
	
	@Test public void testSendAndReceive() {
		utils.clearQueue(TEST_QUEUE);
		utils.clearDirectoryWithPrefix("test");
		String id = "sampleUnitOfWork"+(Math.random()*1000);
		UnitOfWork j = new TestUnitOfWork(10000,id,2000);
		j.setQueueName(TEST_QUEUE);
		String id1 = utils.sendJob(j);
		assertTrue("Job sent, id enequal to null.",id1!=null);
		String id2 = utils.sendJob(j);
		assertTrue("Job exists so it wasn't sent again.",id2==null);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
		List<String> jobs = utils.getJobDirectory();
		assertTrue("Job exists in Job Directory",jobs.contains(TEST_QUEUE+"."+id));
		
		UnitOfWork jComp = null;
		try {
		 jComp = utils.nextJobFromQueue(TEST_QUEUE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		assertTrue("Checking that job received is the job that was injected",jComp.getId().equals(id));
		utils.deleteJob(j.getMessageId(),id,TEST_QUEUE);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
		List<String> jobsComp = utils.getJobDirectory();
		assertFalse("Job does no longer exist in Job Directory",jobsComp.contains(TEST_QUEUE+"."+id));
		
		
		
	}
	
	public static junit.framework.Test suite() {
		return new JUnit4TestAdapter(QueueTest.class);
	}

}
